import time
import cv2
import subprocess
import sys

# 设置gstreamer管道参数
def gstreamer_pipeline(
    capture_width=1280, #摄像头预捕获的图像宽度
    capture_height=720, #摄像头预捕获的图像高度
    display_width=1280, #窗口显示的图像宽度
    display_height=720, #窗口显示的图像高度
    framerate=25,       #捕获帧率
    flip_method=0,      #是否旋转图像
):
    return (
        "nvarguscamerasrc ! "
        "video/x-raw(memory:NVMM), "
        "width=(int)%d, height=(int)%d, "
        "format=(string)NV12, framerate=(fraction)%d/1 ! "
        "nvvidconv flip-method=%d ! "
        "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
        "videoconvert ! "
        "video/x-raw, format=(string)BGR ! appsink"
        % (
            capture_width,
            capture_height,
            framerate,
            flip_method,
            display_width,
            display_height,
        )
    )

if __name__ == "__main__":
    rtmp = sys.argv[1]
    print(rtmp)
    
    capture_width = 1280
    capture_height = 720

    display_width = 1280
    display_height = 720

    framerate = 25			# 帧数
    flip_method = 0			# 方向

    # 创建管道
    cap = cv2.VideoCapture(gstreamer_pipeline(framerate=framerate,flip_method=0), cv2.CAP_GSTREAMER)
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    sizeStr = str(size[0]//2) + 'x' + str(size[1]//2)
    command = ['ffmpeg',
    '-y', '-an',
    '-f', 'rawvideo',
    '-vcodec','rawvideo',
    '-pix_fmt', 'bgr24',
    '-s', sizeStr,
    '-r', '25',
    '-i', '-',
    '-c:v', 'libx264',
    '-pix_fmt', 'yuv420p',
    '-preset', 'ultrafast',
    '-f', 'flv', rtmp]
    pipe = subprocess.Popen(command, shell=False, stdin=subprocess.PIPE)
    while cap.isOpened():
        success, frame = cap.read()
        if success:
            text=time.asctime(time.localtime(time.time()))
            cv2.putText(frame, text, (30,30), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 1)
            frame = cv2.resize(frame,dsize=None,fx=0.5,fy=0.5,interpolation=cv2.INTER_LINEAR)
            pipe.stdin.write(frame.tostring())
    cap.release()
    pipe.terminate()
